import socket
import re

def ipFormatChk(ip_str):
    pattern = r"\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"
    if re.match(pattern, ip_str):
        return True
    else:
        return False


def getipaddr(hostname=''):
    """Given a hostname, perform a standard (forward) lookup and return
          a list of IP addresses for that host."""
    ips = ""
    if ipFormatChk(hostname): return hostname
    if hostname == "":
        hostname = socket.gethostname()
    try:
        ips = socket.gethostbyname_ex(hostname)[2]
        ips = [i for i in ips if i.split('.')[0] != '127']
    except: print "gethostbyname() failed, most likely there is no FQDN available."
    
    if len(ips) != 0:
        # check if we have succes in determining outside IP
        ip = ips[0]
    elif len(ips) == 0 and hostname == socket.gethostname():
        # when we want to determine local IP and did not have succes
        # with gethostbyname_ex then we would like to connect to say... 
        # google.com and determine the local ip address bound to the
        # local socket.
        try:
            print ('connecting to internet to determine local ip')
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.connect(('1.2.3.4', 56))
            ip = s.getsockname()[0]
            del s
        except:
            print ('*** cannot connect to internet in order to \
               determine outside IP address')
            raise Exception
    if len(ip) != 0:
        return ip
    else:
        print ('*** unable to determine outside IP address')
        raise Exception